/**
 * Route Controller层
 */
app.controller('routeCtrl', function ($scope, routeService) {

        // 路由名称正则表达式
        var rgRouteName = "^[A-Z0-9_-]*$";

        // 用户ID
        var userId = 0;

        // 路由名称
        var routeName = '';

        // 路由类型
        var routeType = -1;



        $scope.change = false;
        $scope.requestError = function () {
            $scope.errorMessage = "unknown error!";
        }

        /**
         * 获取用户指定路由
         * @param id
         */
        function findRouteByUserId(id){
            routeService.findRouteByUserId({
                id: id,
                currentPage: 1,
                pageSize: 10,
                action: 'findRouteByUserId'
            },function (data) {
                if(data.state == 'SUCCESS'){
                    $scope.routeList = data.data.routeVO;
                    pageOperation($scope,data.pageInfo);
                }else{
                    bootbox.alert(data.reason);
                }
            });
        }

        /**
         * 初始化用户列表
         */
         function initGWUserList(userId) {
            routeService.initGWUserList({
                action: 'initGWUserList',
                userId: userId
            }, function (data) {
                if(data.state == 'SUCCESS'){
                    $scope.userList = data.data.gwUserVO;
                }else{
                    bootbox.alert(data.reason);
                }
            })
        };

        /**
         * 初始化网关用户树
         */
        routeService.initGWUserTree({
            action: 'initGWUserTree'
        },function (data) {
            if(data.state == 'SUCCESS'){
                var jsonTree = eval('(' + data.data + ')');
                $('#gwUserTree').on('changed.jstree', function (e, data) {
                    var id = data.instance.get_node(data.selected[0]).id;
                    var text = data.instance.get_node(data.selected[0]).text;
                    if(id > 0){
                        userId = id;
                        $scope.userName= text;
                        findRouteByUserId(id);
                    }
                }).jstree({
                    'core':{
                        'data':jsonTree,
                        'themes':{
                            'variant':'large'
                        },
                        'multiple' : false
                    }
                });
            }else{
                bootbox.alert(data.reason);
            }
        });

        /**
         * 查询用户路由
         */
        $scope.queryRoute = function () {
            routeName = $scope.routeName;
            routeType = $scope.routeType;
            $scope.pageSize = $scope.selectPageSize
            routeService.findRouteByNameAndType({
                action: 'findRouteByNameAndType',
                name: routeName,
                type: routeType,
                userId: userId,
                currentPage: 1,
                pageSize: $scope.pageSize
            }, function (data) {
                if(data.state == 'SUCCESS'){
                    $scope.routeList = data.data.routeVO;
                    pageOperation($scope,data.pageInfo);
                }else{
                    bootbox.alert(data.reason);
                }
            });
        };

        /**
         * 查找指定用户下的所有路由
         * @param e
         * @param id
         */
        $scope.findByCondition = function () {
            alert('test');
            routeService.findRouteByNameAndType({
                action: 'findRouteByNameAndType',
                name: routeName,
                type: routeType,
                userId: userId,
                currentPage: $scope.selPage,
                pageSize: $scope.pageSize
            }, function (data) {
                if(data.state == 'SUCCESS'){
                    $scope.routeList = data.data.routeVO;
                    pageOperation($scope,data.pageInfo);
                }else{
                    bootbox.alert(data.reason);
                }
            });
        };

        /**
         * 初始化队列对话框
         */
        function initRouteDialog() {
            $scope.routeForm.name.$setValidity("length", true);
            $scope.routeForm.name.$setValidity("pattern", true);
            $scope.routeForm.name.$setValidity("unique", true);
        }

        /**
         * 新增用户路由
         */
        $scope.createRoute = function () {
            if (userId > 0) {
                //先移除样式然后添加
                $('#glyphicon').removeClass("glyphicon glyphicon-pencil");
                $('#glyphicon').removeClass("glyphicon glyphicon-plus");
                $('#glyphicon').addClass("glyphicon glyphicon-plus");

                $('#dialogRoute').on('show.bs.modal', function () {
                    $scope.title = '新增路由';
                    $scope.route.id = 0;
                    $scope.route.name = '';
                    $scope.route.type = '0';
                    $scope.route.sendAddress = '';
                    $scope.route.recvAddress = '';
                    $scope.route.smi = '';
                    $scope.route.fi = '';
                    $scope.route.an = '';
                    $scope.route.rgs = '';
                    $scope.route.specLable = '';
                    $scope.route.specIndex = '';
                    $scope.route.destination = '';
                });
                initRouteDialog();
                $('#name').removeAttr('disabled', 'disabled');
                $('#dialogRoute').modal('show');
            } else {
                bootbox.alert("请先选择用户");
            }
        };

        /**
         * 修改用户路由
         * @param queue
         */
        $scope.updateRoute = function (route) {
            //先移除样式然后添加
            $('#glyphicon').removeClass("glyphicon glyphicon-pencil");
            $('#glyphicon').removeClass("glyphicon glyphicon-plus");
            $('#glyphicon').addClass("glyphicon glyphicon-pencil");
            $('#dialogRoute').on('show.bs.modal', function () {
                $scope.title = '修改路由';
                $scope.route.id = route.id;
                $scope.route.name = route.name;
                $scope.route.type = route.type.toString();
                $scope.route.sendAddress = route.sendAddress;
                $scope.route.recvAddress = route.recvAddress;
                $scope.route.smi = route.smi;
                $scope.route.fi = route.fi;
                $scope.route.an = route.an;
                $scope.route.rgs = route.rgs;
                $scope.route.specLable = route.specLable;
                $scope.route.specIndex = route.specIndex;
                $scope.route.destination = route.destinationName;
            });
            initRouteDialog();
            $('#name').attr('disabled', 'disabled');
            $('#dialogRoute').modal('show');
        };

        /**
         * 保存用户路由
         * @param route
         */
        $scope.save = function (route) {
            if (route.id == 0) {
                routeService.save({
                    name: route.name,
                    type: route.type,
                    sendAddress: route.sendAddress,
                    recvAddress: route.recvAddress,
                    smi: route.smi,
                    fi: route.fi,
                    an: route.an,
                    rgs: route.rgs,
                    specLable: route.specLable,
                    specIndex: route.specIndex,
                    destinationId: route.destinationId,
                    gwUserId: userId
                }, {}, function (data) {
                    if (data.state == 'SUCCESS') {
                        bootbox.alert('保存成功',function(){
                            $('#dialogRoute').modal('hide');
                            $scope.queryRoute();
                        });
                    } else {
                        bootbox.alert(data.reason);
                    }
                }, $scope.requestError);
            } else {
                routeService.updateRoute({
                    id: route.id,
                    name: route.name,
                    type: route.type,
                    sendAddress: route.sendAddress,
                    recvAddress: route.recvAddress,
                    smi: route.smi,
                    fi: route.fi,
                    an: route.an,
                    rgs: route.rgs,
                    specLable: route.specLable,
                    specIndex: route.specIndex,
                    destinationId: route.destinationId,
                    gwUserId: userId
                }, function (data) {
                    if (data.state == 'SUCCESS') {
                        bootbox.alert('保存成功',function(){
                            $('#dialogRoute').modal('hide');
                            $scope.queryRoute();
                        });
                    } else {
                        bootbox.alert(data.reason);
                    }
                }, $scope.requestError);
            }
        };

        /**
         * 删除用户路由
         * @param id
         */
        $scope.deleteRoute = function (id) {
            bootbox.confirm({
                title: "系统提示",
                message: "确认是否要删除该路由？",
                buttons: {
                    cancel: {
                        className: 'btn-sm',
                        label: '<i class="glyphicon glyphicon-remove"></i> 取消'
                    },
                    confirm: {
                        className: 'btn-sm btn-success',
                        label: '<i class="glyphicon glyphicon-ok"></i> 确定'
                    }
                },
                callback: function (result) {
                    if (result) {
                        routeService.delete({
                            id: id
                        }, function (result) {
                            if (result.state == 'SUCCESS') {
                                bootbox.alert('删除成功',function(){
                                    $scope.queryRoute();
                                });
                            } else {
                                bootbox.alert(data.reason);
                            }
                        }, $scope.requestError)
                    }
                }
            });
        };

        /**
         * 批量删除用户路由
         */
        $scope.deleteSeletedRoute = function () {
            var chk_value = [];
            $('input[name="checks"]:checked').each(function () {
                chk_value.push($(this).val());
            });
            if (chk_value.length == 0) {
                bootbox.alert('未选择用户路由');
                return;
            }
            $scope.deleteRoute(chk_value);
        };

        $scope.close = function () {
            angular.element('#dialogRoute').modal('hide');
            angular.element('#dialogDestination').modal('hide');
        };

        /**
         * 校验队列名称
         */
        $scope.checkName = function (routeName) {
            if (!routeName.match(rgRouteName)) {
                $scope.routeForm.name.$setValidity("pattern", false);
                return;
            } else {
                $scope.routeForm.name.$setValidity("pattern", true);
            }
            routeService.checkName({
                    action: 'checkName',
                    routeName: routeName
                }, function (data) {
                    if (data.state != 'SUCCESS') {
                        if (data.code == 0) {
                            $scope.routeForm.name.$setValidity("unique", false);
                            bootbox.alert(data.reason);
                        }
                    } else {
                        $scope.routeForm.name.$setValidity("unique", true);
                    }
                }
            )
            ;
        };

        /**
         * 打开目的用户对话框
         */
        $scope.showDestinationDialog = function (destination) {

            // 初始化对话框，清空复选框
            $('#selectAll').removeAttr("checked", "checked");
            $('input[name="destinationUser"]').each(function () {
                $(this).removeAttr("checked", "checked");
            });

            // 初始化用户列表
            initGWUserList(userId);
            $('#dialogDestination').modal('show').on('shown.bs.modal',function(){
                if(destination != null){
                    $('input[name="destinationUser"]').each(function(){
                        for(var i = 0; i < destination.length;i++){
                            if($(this).parent().parent().find('td').eq(1).text() == destination[i]){
                                $(this).prop("checked", "checked");
                            }
                        }
                    });
                }
            });
        }

        /**
         * 保存目的用户
         */
        $scope.saveDestination = function () {

            // 目的用户ID
            var selectedUserId = new Array();

            // 目的用户名称
            var selectedUserName = new Array();

            // 保存选中目的用户
            $('input[name="destinationUser"]:checked').each(function () {
                selectedUserId.push($(this).val());
                selectedUserName.push($(this).parent().parent().find('td').eq(1).text());
            });
            if (selectedUserName.length > 0) {
                $scope.route.destination = selectedUserName;
                $scope.route.destinationId = selectedUserId;
                angular.element('#destination').val(selectedUserName);
                angular.element('#dialogDestination').modal('hide');
            } else {
                $scope.route.destinationId = [];
                angular.element('#destination').val('');
                angular.element('#dialogDestination').modal('hide');
            }
        };

        /**
         * 取消保存目的用户
         */
        $scope.cancelDestination = function () {
            angular.element('#dialogDestination').modal('hide');
        };

        /**
         * 文本框校验 获取焦点为false 丢失焦点为true
         */
        $scope.change = function (flag) {
            $scope.changed = flag;
        }
        /**
         * 清除模态框
         */
        $scope.clear = function () {
            $scope.route.sendAddress = '';
            $scope.route.recvAddress = '';
            $scope.route.smi = '';
            $scope.route.fi = '';
            $scope.route.an = '';
            $scope.route.rgs = '';
            $scope.route.specLable = '';
            $scope.route.specIndex = '';
            $scope.route.destination = '';
        }
    }
)
;

